<?php
/* +----------------------------------------------------------------------
// | 	xaoam.com
// |	author:am
// |	gitee:https://gitee.com/xaoam/amAdmin
// |	email:hi@xaoam.com
// |	
// +----------------------------------------------------------------------*/
namespace app\admin\model;

use think\Model;
use think\Db;
use app\admin\validate\User as UserCheck;

class UserM extends Model {
	protected $table = "am_user";
	protected function getSexAttr($value)
    {
    	$sex = [0=>'保密',1=>'男',2=>'女'];
    	return $sex[$value];
    }
	protected function getAdminAttr($value,$data){
		        
				if($data['id'] == 1){
					return '超级管理员';
				}else{
					$admin = [0=>'普通用户',1=>'管理员'];
					  return $admin[$data['admin']];
	}
		      
	}
	/*验证器,验证*/
	protected function checkData($act,$data){
		$check = new UserCheck;
		if (!$check->scene($act)->check($data)) {
			$res['msg'] = $check->getError();
			$res['code'] = 0;
			header('Content-type:application/json; charset=utf-8');
			echo json_encode($res);
			exit();
		}
	}
	public function lists($limit){
		return $this->field('id,username,tel,email,admin')->paginate($limit);
	}
	public function find($data){
			return $this->where($data)->find();
	}
	public function add($data){
		$this->checkData('add',$data);
		print_r($data);
		$data['admin']   = isset($data['admin'])?1:0;
		if($data['passwd']){
			$data['salt']	= getSalt();
			$data['passwd'] = getHash($data['passwd'],$data['salt']);
		}
		return $this->allowField('true')->create($data);
    }
	/*
	先查询,$data->username字段不存在,传递查询回原字段,(普通管理员编辑用户判断)
			$data->admin,当前登陆用户为超管时,可以修管理员标识
			$user->salt 获取salt,
			
	*/
    public function edit($data){
		if(!isset($data['passwd'])){
		$this->checkData('emptypwd',$data);			
		}else{
		$this->checkData('edit',$data);			
		}
		if($this->checkUser($data)){
			$user = $this->get($data['id']);
			$user->email    = $data['email'];
			$user->sex =	$data['sex'];
			$user->tel    = $data['tel'];
			if(app('session')->get('user_info.id')  == 1){
				$user->admin   = isset($data['admin'])?1:0;
			}
			if(isset($data['passwd']) && !empty($data['passwd'])){
				$user->salt = getSalt();
				$user->passwd  = getHash($data['passwd'],$user['salt']);
			}else{
				unset($data['passwd']);
			}
			return $user->save();			
		}

    }
	public function cue($data){
		$this->checkData('cue',$data);
		$this->checkUser($data);
		return $this->save([
		    $data['field']  => $data['value'],
		],['id' => $data['id']]);
	}
	public function dels($data){
		foreach($data as $row){
			$d['id']  = $row;
			$this->checkData('del',$d);
		}
		 return $this->destroy($data);
	}
	/*普通管理员->无权修改用户名->用户不存在->true*/
	/*管理员->修改用户名->查询->null,没有改变->true*/
	protected function checkUser($data){
		if(isset($data['username'])){
			$res = $this->find(['username'=>$data['username']]);
			if($res === null || $res['id'] == $data['id']){
				return true;
			}
			return false;
		}else{
			return true;
		}

	}
}	